package com.ronds.webtest.util;

import com.ronds.webtest.Listener.WebEventListener;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

/**
 * Created by zhanghui on 2017/2/7.
 */
public class WebDriverManager {

    private static WebDriver driver;
    private static WebDriverWait wait;
    private static WebDriverWait wait2;
    private static long TIME_OUT_IN_SECONDS = 10L;
    private static String os = System.getProperty("os.name");

    private WebDriverManager() {
        //
    }

    public static WebDriver getDriver() {
        if(driver==null) {
            String driverType = System.getProperty("web.driver");
            if(driverType!=null && driverType.equals("firefox")) {
                if(os.contains("Windows")) {
                    System.setProperty("webdriver.gecko.driver", "drivers/windows/geckodriver-v0.15.0.exe");
                } else {
                    System.setProperty("webdriver.gecko.driver", "drivers/mac/geckodriver-v0.15.0");
                }
                driver = new FirefoxDriver();
                driver.manage().window().maximize();
            } else {
                if(os.contains("Windows")) {
                    System.setProperty("webdriver.chrome.driver", "drivers/windows/chromedriver-2.42.exe");
                } else {
                    System.setProperty("webdriver.chrome.driver", "drivers/mac/chromedriver-2.46");
                }
                driver = new EventFiringWebDriver(new ChromeDriver()).register(new WebEventListener());
            }
        }
        return driver;
    }

    public static WebDriverWait getWait() {
        if(wait==null) {
            wait = new WebDriverWait(getDriver(), TIME_OUT_IN_SECONDS);
        }
        return wait;
    }

    public static WebDriverWait getWait2() {
        if(wait2==null) {
            wait2 = new WebDriverWait(getDriver(), 20);
        }
        return wait2;
    }

}
